/**
 * Created by Ysssssss on 20/12/15.
 */

import { PACKAGE_PRODUCT_PAGE } from '../../../constants/route';
import { arr2Obj } from '../../../common/utils';
import { tipToast, navToAction } from '../../../common/env';

const getALlStandard = (arrays) => {
    if (!arrays.length) return []
    if (arrays.length === 1) return arrays[0].map(item => [ item ])
    return arrays.reduce((arr1, arr2) =>
        arr1.flatMap(propertyName =>
            arr2.map(propertyName2 =>
                Array.isArray(propertyName) ? [...propertyName, propertyName2] : [propertyName, propertyName2]
            )
        )
    )
}

Page({
    data: {
        properties: [{
            key: '测试',
            values: ['酸', '甜' ,'苦', '辣']
        }],
        propertyError: [],
        _standardPriceMap: {},
        _propertiesMapBackup: {}
    },

    onLoad() {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', (data) => {
            const { standardPriceMap, properties } = data
            this.setData({
                properties,
                _propertiesMapBackup: arr2Obj(properties, 'key', 'remotePK'),
                _standardPriceMap: standardPriceMap,
            })
        })
    },

    handlePropertyChange (e) {
        const { properties } = this.data
        const { index } = e.currentTarget.dataset
        this.setData({
            properties: [
                ...properties.slice(0, index),
                e.detail,
                ...properties.slice(index + 1)
            ]
        })
    },

    handlePropertyDelete (e) {
        const { properties } = this.data
        const { index } = e.currentTarget.dataset
        this.setData({
            properties: [
                ...properties.slice(0, index),
                ...properties.slice(index + 1)
            ]
        })
    },

    addProperty () {
        const { properties } = this.data
        this.setData({
            properties: [
                ...properties,
                {
                    key: '',
                    values: [],
                }
            ]
        })
    },

    nextStep () {
        const { properties, _standardPriceMap } = this.data
        let keyArr = []
        let valuesArr = []
        let propertyErrorMessage = ''
        let propertyError = properties.map(property => {
            let keyValid = false
            if (!propertyErrorMessage && !property.key) {
                propertyErrorMessage = '规格名称不能为空'
                keyValid = true
            }
            if (!propertyErrorMessage && keyArr.includes(property.key)) {
                propertyErrorMessage = '规格名称不能重复'
                keyValid = true
            }
            if (!propertyErrorMessage && !property.values.length) {
                propertyErrorMessage = `[${property.key}]：请至少填写一项具体规格`
            }
            keyArr.push(property.key)
            return {
                keyValid,
                valuesValid: property.values.map(sub => {
                    let _subValid = !sub || valuesArr.includes(sub)
                    if (!propertyErrorMessage && !sub) {
                        propertyErrorMessage = '具体规格名称不能为空'
                    }
                    if (!propertyErrorMessage && valuesArr.includes(sub)) {
                        propertyErrorMessage = '具体规格名称不能重复'
                    }
                    valuesArr.push(sub)
                    return _subValid
                })
            }
        })
        if (propertyErrorMessage) {
            tipToast(propertyErrorMessage)
            this.setData({
                propertyError
            })
        } else {
            let attributesMap = {}
            let _standardListArr = getALlStandard(properties.map(property => {
                property.values.forEach(value => {
                    attributesMap[value] = {
                        key: property.key,
                        value
                    }
                })
                return property.values
            }))
            navToAction(PACKAGE_PRODUCT_PAGE['productSku'], {}, {
                success: function(res) {
                    // 通过eventChannel向被打开页面传送数据
                    res.eventChannel.emit(
                        'acceptDataFromOpenerPage',
                        {
                            properties,
                            standardList: _standardListArr.map(
                                standard => ({
                                    id: standard.join('/'),
                                    price: _standardPriceMap[standard.join('/')] || '',
                                    attributes: standard.map(value => attributesMap[value]),
                                })
                            )
                        }
                    )
                }
            })
        }
    }
})